import DOMPurify from 'dompurify';
import Link from 'next/link';

export default function Articles({ articles, theme }) {
    return (
        <main className={`w-full md:w-[70%] ${theme === 'dark' ? 'bg-black text-white' : 'bg-gray-100 text-black'} p-4`}>
            {/* 这里的 ml-4 和 ml-12 用来保证标题与文章区域对齐 */}
            <h2 className={`text-2xl font-bold mb-4 ${theme === 'dark' ? 'text-white' : 'text-black'} ml-4 md:ml-12`}>最新文章</h2>

            {/* 使用 ml-4 和 ml-12 让文章区域与标题对齐 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 ml-4 md:ml-12">
                {articles.slice(0, 9).map((article, index) => {
                    const imageUrls = JSON.parse(article.imageUrls);
                    const backgroundImage = imageUrls.length > 0 ? imageUrls[0] : '/login7-1.jpg'; // 用默认图片代替

                    return (
                        <Link href={`/article/${article.id}`} key={article.id} className={index === 0 ? 'col-span-2' : ''}>
                            <article
                                className={`relative mb-4 p-4 cursor-pointer ${theme === 'dark' ? 'bg-black text-white' : 'bg-white text-black'} rounded-lg shadow ${index === 0 ? 'col-span-2 h-[28rem]' : 'h-[18rem]'}`}
                                style={{ backgroundImage: `url(${backgroundImage})`, backgroundSize: 'cover', backgroundPosition: 'center', backgroundRepeat: 'no-repeat' }}
                            >
                                {/* 通过 absolute 定位文字到下半部分 */}
                                <div className="absolute bottom-0 left-0 right-0 bg-opacity-60 bg-black text-white p-4">
                                    <h3 className="text-xl font-semibold mb-2">{article.title}</h3>
                                    <div
                                        className="text-white"
                                        dangerouslySetInnerHTML={{
                                            __html: DOMPurify.sanitize(article.content.substring(0, 100) + '...'),
                                        }}
                                    />
                                </div>
                            </article>
                        </Link>
                    );
                })}
            </div>
        </main>
    );
}
